package com.thinksmart.qfilemanager;

import android.content.Context;
import android.content.SharedPreferences;
import android.support.v7.app.ActionBar;
import android.app.ProgressDialog;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Looper;
import android.os.Message;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.EditText;
import android.widget.Toast;
import com.qnap.qdk.qtshttp.QtsHttpServer;
import com.qnap.qdk.qtshttp.QtsHttpServerInfo;
import com.qnap.qdk.qtshttp.QtsHttpStationType;
import com.qnap.qdk.qtshttp.exception.QtsHttpAuthorizationFailedException;
import com.qnap.qdk.qtshttp.exception.QtsHttpNetworkTimeoutException;
import com.qnap.qdk.qtshttp.filestation.IQtsHttpFileStation;

public class loginActivity extends AppCompatActivity implements  OnClickListener{
    private EditText mSrvIP;
    private EditText mPort;
    private EditText mUser;
    private EditText mPwd;
    private CheckBox mRemember;
    private CheckBox mSSL;

    private boolean mIsRememberPwd;
    private boolean mIsSSL;
    private String mUserName;
    private String mPassword;

    private QtsHttpServer mServer;
    private H mHandler;
    public static IQtsHttpFileStation mFileStation;
    private static SharedPreferences mSharePref = null;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        mSharePref = getPreferences(Context.MODE_PRIVATE);

        loadData();

        ActionBar actionBar = this.getSupportActionBar();
        actionBar.setLogo(R.mipmap.ic_launcher);
        actionBar.setDisplayShowHomeEnabled(true);
        actionBar.setDisplayUseLogoEnabled(true);
        setContentView(R.layout.activity_login);

        ((Button)findViewById(R.id.btnLogin)).setOnClickListener(this);
        mSrvIP = (EditText)findViewById(R.id.etIP);
        mPort = (EditText)findViewById(R.id.etPort);
        mUser = (EditText)findViewById(R.id.etUser);
        mPwd = (EditText)findViewById(R.id.etPwd);
        mRemember = (CheckBox)findViewById(R.id.chkRemember);
        mSSL = (CheckBox)findViewById(R.id.chkSSL);
        mHandler = new H();

        ((Button)findViewById(R.id.btnLogin)).setOnClickListener(this);
        mRemember.setOnClickListener(this);

        initData();
    }

    private final class H extends Handler {
        private static final int MSG_LOGINGING = 0;
        private static final int MSG_LOGIN = 1;
        private static final int MSG_LOGOUT = 2;
        private static final int MSG_CLOSE_APP = 3;

        private ProgressDialog progDlg =  new ProgressDialog(loginActivity.this);
        String message = "";
        Toast toast = null;

        private H() {
            super(Looper.getMainLooper());
        }

        @Override
        public void handleMessage(Message msg) {
            switch (msg.what) {
                case MSG_LOGIN:
                    progDlg.dismiss();
                    message = msg.getData().getString("message");
                    toast = Toast.makeText(loginActivity.this, message, Toast.LENGTH_SHORT);
                    toast.show();
                    break;
                case  MSG_LOGINGING:
                    CharSequence title = getString(R.string.progdlg_title);
                    CharSequence body = getString(R.string.progdlg_body_logining);

                    progDlg.setProgressStyle(ProgressDialog.STYLE_SPINNER);
                    progDlg.setTitle(title);
                    progDlg.setMessage(body);
                    progDlg.show();
                    break;
                case MSG_LOGOUT:
                    break;
                case MSG_CLOSE_APP:
                    break;
            }
        }
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.btnLogin:
                Thread thread = new Thread() {
                    @Override
                    public void run() {
                        String strSrvIP = mSrvIP.getText().toString();
                        int port = Integer.valueOf(mPort.getText().toString());
                        String strUser = mUser.getText().toString();
                        String strPwd = mPwd.getText().toString();
                        mIsRememberPwd = mRemember.isChecked();
                        mIsSSL = mSSL.isChecked();
                        String agentName = "QNAP QtsHttp Java Sample Code for Android 1.0.0";
                        QtsHttpServerInfo svrInfo = new QtsHttpServerInfo(strSrvIP, strUser, strPwd, mIsSSL,  "");
                        mServer = new QtsHttpServer(svrInfo);
                        try {
                            if (mIsSSL) {
                                mServer.setFileStationSSLPortNum(port);
                            }else {
                                mServer.setFileStationPortNum(port);
                            }
                            mServer.setAgentName(agentName);
                        }catch (Exception e) {
                            e.printStackTrace();
                        }

                        Message msg = new Message();
                        Bundle data = msg.getData();
                        boolean isLogin = false;

                        try {
                            mHandler.obtainMessage(H.MSG_LOGINGING).sendToTarget();

                            mServer.login(QtsHttpStationType.QTS_HTTP_STATION_TYPE_FILE_STATION);
                            data.putString("message", "Login success");
                            isLogin = true;
                            data.putBoolean("isLogin", isLogin);
                            mFileStation = mServer.openFileStation();
                        }catch (QtsHttpNetworkTimeoutException e) {
                            data.putString("message", "Timeout");
                            data.putBoolean("isLogin", isLogin);
                        }catch (QtsHttpAuthorizationFailedException e) {
                            data.putString("message", "Login failed");
                            data.putBoolean("isLogin", isLogin);
                        }catch (Exception e) {
                            data.putString("message", "Error");
                            data.putBoolean("isLogin", isLogin);
                        }

                        msg.what = H.MSG_LOGIN;
                        msg.setData(data);
                        mHandler.sendMessage(msg);

                        if (isLogin) {
                            Intent intent = new Intent();
                            intent.setClass(loginActivity.this, fileListActivity.class);

                            Bundle bundle = new Bundle();
                            bundle.putString("relativePath", "/");
                            intent.putExtras(bundle);
                            saveData();
                            startActivity(intent);
                            finish();
                        }
                    }
                };
                thread.start();
                break;
            case R.id.chk_Select:
                mIsRememberPwd = mRemember.isChecked();
                break;
            default:
                break;
        }

    }

    private void loadData() {
        if (mSharePref != null) {
            if (mSharePref.getBoolean("isRemember", false)) {
                mUserName = mSharePref.getString("userName", String.valueOf(R.string.hint_user_name));
                mPassword = mSharePref.getString("passWord", null);
                mIsRememberPwd = mSharePref.getBoolean("isRemember", false);
            }
        }
    }

    private void saveData() {
        if (mSharePref != null) {
            SharedPreferences.Editor editor = mSharePref.edit();
            editor.putBoolean("isRemember", mIsRememberPwd);
            if (mIsRememberPwd) {
                editor.putString("userName", mUser.getText().toString());
                editor.putString("passWord", mPwd.getText().toString());
            }
            editor.commit();
        }
    }

    private void initData() {
        mRemember.setChecked(mIsRememberPwd);
        if (mIsRememberPwd) {
            mUser.setText(mUserName);
            mPwd.setText(mPassword);
        }
    }
}
